"""
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为：“对于有根树 T 的两个结点 p、q，最近公共祖先表示为一个结点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”

例如，给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

链接：https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
"""

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'):
        # fu_q, fu_p = [], []
        # tmp = []
        # def dfs(root):
        #     if not root: return
        #     tmp.append(root)
        #     if root == p:
        #         fu_p.extend(tmp)
        #     elif root == q:
        #         fu_q.extend(tmp)
        #     dfs(root.left)
        #     dfs(root.right)
        #     tmp.pop()
        # dfs(root)
        # for i in fu_q[::-1]:
        #     for j in fu_p[::-1]:
        #         if i == j:
        #             return i
        White, Gray = 0, 1
        fu_q, fu_p = [], []
        tmp = []
        stack = [[White, root]]
        while stack:
            color, node = stack.pop()
            if not node: continue
            if color == White:
                tmp.append(node)
                stack.append([Gray, node])
                stack.append([White, node.right])
                stack.append([White, node.left])
            else:
                if node == p:
                    fu_p.extend(tmp)
                elif node == q:
                    fu_q.extend(tmp)
                tmp.pop()
        for i in fu_p[::-1]:
            for j in fu_q[::-1]:
                if i == j:
                    return i